<template>
  <el-card shadow="hover" class="mt-20">
    <el-form
      ref="SpuFormRef"
      :model="SpuForm"
      label-width="120px"
      :rules="spuRules"
    >
      <el-form-item label="SPU名称" prop="spuName">
        <el-input
          v-model="SpuForm.spuName"
          placeholder="请输入SPU名称"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌" prop="tmId">
        <el-select v-model="SpuForm.tmId" placeholder="请选择" size="small">
          <el-option
            :label="t.tmName"
            :value="t.id"
            v-for="t in trademarkList"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" prop="description">
        <el-input
          type="textarea"
          v-model="SpuForm.description"
          :rows="3"
          placeholder="请输入SPU描述"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片" prop="spuImageList">
        <el-upload
          action="http://gmall-h5-api.atguigu.cn/admin/product/upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          v-model="SpuForm.spuImageList"
          :file-list="SpuForm.spuImageList || []"
          :on-success="handleSuccess"
          :before-upload="beforeAvatarUpload"
          accept="image/jpeg,image/png"
        >
          <i class="el-icon-plus"></i>
          <el-icon><Plus /></el-icon>
          <template #tip>
            <div class="el-upload__tip">只能上传jpg/png文件，且不超过200kb</div>
          </template>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" prop="spuSaleAttrList">
        <el-select
          v-model="selectedBaseSaleAttr"
          placeholder="请选择"
          size="small"
          class="mr-10"
        >
          <el-option
            :label="attr.name"
            :value="`${attr.id} : ${attr.name}`"
            v-for="attr in filterBaseSaleAttrList"
          ></el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="addSaleAttr"
        >
          添加销售属性
        </el-button>
        <el-table
          :data="SpuForm.spuSaleAttrList"
          border
          style="width: 100%"
          class="mt-20"
        >
          <el-table-column
            prop="index"
            label="属性"
            width="80"
            type="index"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性名" width="180">
          </el-table-column>
          <el-table-column prop="spuSaleAttrValueList" label="属性值列表">
            <template v-slot="{ row }">
              <el-tag
                v-for="(spuSaleAttrValue, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row.spuSaleAttrValueList, index)"
                class="mr-10"
                size="small"
                type="success"
              >
                {{ spuSaleAttrValue.saleAttrValueName }}
              </el-tag>
              <el-input
                ref="inputRef"
                placeholder="请输入属性值"
                size="mini"
                class="addOrUpdateSpu_input"
                v-model="saleAttrValueName"
                v-if="row.isShowEdit"
                @keyup.enter.native="switchShow(row)"
                @blur="switchShow(row)"
              ></el-input>
              <el-button
                type="default"
                icon="el-icon-plus"
                size="small"
                v-else
                @click="switchEdit(row)"
              ></el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" align="center">
            <template v-slot="{ row, index }">
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="removeSpuSaleAttr(index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="submit">保存</el-button>
        <el-button type="default" size="small" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { getTrademarkListApi } from "@/api/product/trademark";
import {
  baseSaleAttrListApi,
  addSpuInfoApi,
  getSpuImageListApi,
  getSpuSaleAttrListApi,
  updateSpuInfoApi,
} from "@/api/product/spu";
import { mapState } from "vuex";

export default {
  name: "AddOrUpdateSpu",
  data() {
    const spuSaleAttrListValidator = (rule, value, callback) => {
      // console.log(rule, value, callback);
      /*
    rule 校验规则信息，包含规则名称等内容
    value 校验的数据
    callback 一个函数（必须要调用）
      callback() 表单校验通过
      callback(new Error('错误信息')) 表单校验失败，参数就是失败提示的错误信息
  */
      //  1.销售属性必须有值
      if (!value.length) {
        callback(new Error("请至少添加一个销售属性"));
        return;
      }
      // 2.每一个销售属性的销售属性值列表至少添加一个销售属性值
      if (
        value.some((spuSaleAttr) => !spuSaleAttr.spuSaleAttrValueList.length)
      ) {
        callback(new Error("每一个销售属性至少添加一个销售属性值"));
        return;
      } else {
        callback();
      }
    };
    return {
      SpuForm: {
        description: "",
        id: undefined,
        spuName: "",
        tmId: undefined,
        spuImageList: [],
        spuSaleAttrList: [],
      },
      spuRules: {
        // id: undefined,
        spuName: [
          { required: true, message: "请输入spu名称", trigger: "blur" },
        ],
        tmId: [{ required: true, message: "请选择品牌", trigger: "change" }],
        description: [
          { required: true, message: "请输入spu描述", trigger: "blur" },
          // { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" },
        ],
        spuImageList: [{ required: true, message: "请上传SPU图片" }],
        spuSaleAttrList: [
          // 数组需要自定义校验规则，判断数组里面是否有值
          {
            required: true, // 显示*号，同时也是必填项
            validator: spuSaleAttrListValidator, // validator属性:函数,函数里面对数据进行校验
          },
        ],
      },
      selectedBaseSaleAttr: "",
      saleAttrValueName: "",
      trademarkList: [],
      baseSaleAttrList: [],
      // 预览图片
      dialogImageUrl: "",
      dialogVisible: false,
    };
  },
  computed: {
    ...mapState("category", ["category3Id"]),
    ...mapState("spu", ["spu"]),
    filterBaseSaleAttrList() {
      return this.baseSaleAttrList.filter(
        (item) =>
          !this.SpuForm.spuSaleAttrList.some(
            (attr) => attr.baseSaleAttrId === item.id
          )
      );
    },
  },
  async mounted() {
    const spuId = this.spu.id;
    if (spuId) {
      this.SpuForm = this.spu;
      // 获取spu图片列表和属性列表
      const res = await Promise.allSettled([
        getSpuImageListApi(spuId),
        getSpuSaleAttrListApi(spuId),
      ]);
      console.log(res);
      const spuImageList = res[0].value.data;
      this.SpuForm.spuImageList = spuImageList.map((img) => {
        return {
          name: img.imgName,
          url: img.imgUrl, // 图片地址（不填就渲染不了图片）
          response: {
            data: img.imgUrl,
          },
        };
      });
      this.SpuForm.spuSaleAttrList = res[1].value.data;
    }
    // 获取品牌和销售属性
    const res = await Promise.allSettled([
      getTrademarkListApi(),
      baseSaleAttrListApi(),
    ]);
    this.trademarkList = res[0].value.data;
    this.baseSaleAttrList = res[1].value.data;
  },

  methods: {
    async submit() {
      // console.log(  this.$refs.SpuFormRef);
      await this.$refs.SpuFormRef.validate();

      const SpuForm = this.SpuForm;
      const data = {
        category3Id: this.category3Id,
        ...SpuForm,
        // 组件表单收集的到图片数据是 name，response.data
        // 而发送请求需要的图片数据是 imgName imgUrl
        spuImageList: SpuForm.spuImageList.map((img) => {
          return {
            imgUrl: img.response.data,
            imgName: img.name,
          };
        }),
      };
      if (SpuForm.id) {
        await updateSpuInfoApi(data);
        this.$message.success("spu修改成功");
      } else {
        // 发送添加spu请求
        await addSpuInfoApi(data);
        this.$message.success("spu添加成功");
      }

      this.cancel();
      // 关闭清空vuex的spu数据
    },
    // 添加销售属性
    addSaleAttr() {
      // const id = this.selectedBaseSaleAttr.split(":")[0];
      // const name = this.selectedBaseSaleAttr.split(":")[1];
      const [id, name] = this.selectedBaseSaleAttr.split(":");
      this.SpuForm.spuSaleAttrList.push({
        baseSaleAttrId: +id, // 基础销售属性id
        saleAttrName: name, // 基础销售属性的name
        spuSaleAttrValueList: [], // 销售属性值列表
        isShowEdit: false, //  编辑和显示切换的标识，默认显示显示模式
      });
      this.selectedBaseSaleAttr = "";
    },
    switchEdit(row) {
      row.isShowEdit = true;
      this.$nextTick(() => {
        // console.log(this.$refs.inputRef);
        this.$refs.inputRef.focus();
      });
      // this.$refs.inputRef.focus()//获取不到
    },
    // 切换显示模式
    switchShow(row) {
      // 如果输入内容重复，不进行添加 后还是编辑模式
      let saleAttrValueName = this.saleAttrValueName;
      if (
        row.spuSaleAttrValueList.some((item) => {
          return saleAttrValueName === item.saleAttrValueName;
        })
      ) {
        this.$message.waring("不同添加相同的属性值");
        return;
      }
      // 如果输入内容为空，不添加后显示模式
      if (!saleAttrValueName.trim()) return;
      row.spuSaleAttrValueList.push({
        baseSaleAttrId: row.baseSaleAttrId,
        saleAttrValueName,
      });
      row.isShowEdit = false;

      this.saleAttrValueName = "";
    },
    // 删除属性值
    handleClose(spuSaleAttrValueList, index) {
      spuSaleAttrValueList.splice(index, 1);
    },
    // 删除属性
    removeSpuSaleAttr(index) {
      this.SpuForm.spuSaleAttrList.splice(index, 1);
    },
    // 取消
    cancel() {
      this.$emit("setIsShow", 1);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传图片成功
    handleSuccess(response, file, fileList) {
      // console.log(response, file, fileList);
      this.SpuForm.spuImageList = fileList;
    },
    // 上传图片之前
    beforeAvatarUpload(file) {
      // const isJPG = file.type === "image/jpeg";
      // const isLt2M = file.size / 1024 / 1024 < 2;
      const imgType = ["image/jpeg", "image/png"];
      const isLt2KB = file.size / 1024;
      if (!imgType.includes(file.type)) {
        this.$message.error("上传头像图片只能是 JPG 格式或 PNG 格式!");
        return false;
      }
      if (file.size / 1024 > 200) {
        this.$message.error("上传头像图片大小不能超过 200kb!");
        return false;
      }
      return imgType && isLt2KB;
    },
  },
};
</script>

<style scoped>
/* 上传组件 */
/* 修改子组件样式 */
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.tip {
  font-size: 12px;
}
.addOrUpdateSpu_input {
  width: 180px;
}
</style>
